package com.sphd.beautysalon.activitys;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.beautysalon.interfaces.MychangetabInterface;
import com.sphd.beautysalon.view.RegistView;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.activitys.RegisterActivityPermissionsDispatcher;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.presenter.RegistPresenterImpl;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.MyViewGroup;
import com.wzh.frame.utils.JsonUtil;
import com.wzh.frame.utils.MyUtils;
import com.wzh.frame.views.FiexoDialog;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 注册
 */
@RuntimePermissions
public class RegisterActivity extends BaseActivity implements Handler.Callback, RegistView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.market_id)
    MaterialEditText marketId;
    @BindView(R.id.phone)
    MaterialEditText phone;
    @BindView(R.id.password_old)
    MaterialEditText passwordOld;
    @BindView(R.id.password)
    MaterialEditText password;
    @BindView(R.id.password_again)
    MaterialEditText passwordAgain;
    @BindView(R.id.register_getnum)
    Button registerGetnum;
    @BindView(R.id.yanzhangma)
    MaterialEditText yanzhangma;
    @BindView(R.id.yzm_relativelayout)
    RelativeLayout yzmRelativelayout;
    @BindView(R.id.next_btn)
    Button nextBtn;
    @BindView(R.id.cg_name)
    MaterialEditText cgName;
    @BindView(R.id.birthday_textview)
    TextView birthdayTextview;
    @BindView(R.id.boy)
    RadioButton boy;
    @BindView(R.id.girl)
    RadioButton girl;
    @BindView(R.id.sex_radiogroup)
    RadioGroup sexRadiogroup;
    @BindView(R.id.restaurant_num)
    MaterialEditText restaurantNum;
    @BindView(R.id.update)
    Button update;
    @BindView(R.id.MyViewGroup1)
    MyViewGroup mvg;
    @BindView(R.id.content_register)
    RelativeLayout contentRegister;
    //此APPKEY仅供测试使用，且不定期失效，请到mob.com后台申请正式APPKEY
    private static String APPKEY = "1821134b197de";
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "6f55db8a086cbad12b69def6c81d71f2";
    boolean ready = false;
    private TimeCount time;//倒计时类的实现
    boolean capacity = false;//智能验证
    private RegistPresenterImpl registPresenter;
    private boolean checkOk = false;//0为初始化进入 1为验证完成 2回转
    private Calendar calendar; //通过Calendar获取系统时间
    private String cg_sex = "男";
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mvg.setCallBack(new MyChagneTab());
        sexRadiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton) findViewById(radioButtonId);
                //更新文本内容，以符合选中项
                cg_sex = rb.getText().toString();
            }
        });
    }

    private void initView() {
        //弹出注册对话框
        showRegisterdialog();
        setTitleBar(toolbar, "注册");
        registPresenter = new RegistPresenterImpl(this);
        calendar = Calendar.getInstance();
        intent = getIntent();
    }

    @OnClick({R.id.register_getnum, R.id.next_btn, R.id.update, R.id.birthday_textview})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_getnum:
                checkPhone();
                break;
            case R.id.next_btn:
                checkAll();
                break;
            case R.id.update:
                if (TextUtils.isEmpty(cgName.getText().toString().trim())) {
                    showErrorDialog("超管名称为空");
                } else {
                    if (birthdayTextview.getText().toString().trim().equals("年.月.日")) {
                        showErrorDialog("请选择生日");
                    } else {
                        if (TextUtils.isEmpty(restaurantNum.getText().toString().trim())) {
                            showErrorDialog("请输入店铺数量");
                        } else {
                            if (Integer.parseInt(restaurantNum.getText().toString().trim()) < 1) {
                                showErrorDialog("店铺数量最小为1");
                            } else {
                                if (TextUtils.isEmpty(marketId.getText().toString().trim())) {
                                    mvg.snapToScreen(0);
                                    showErrorDialog("销售员ID为空");
                                } else {
                                    if (TextUtils.isEmpty(password.getText().toString().trim())) {
                                        mvg.snapToScreen(0);
                                        showErrorDialog("密码不能为空");
                                    } else {
                                        if (TextUtils.isEmpty(passwordAgain.getText().toString().trim())) {
                                            mvg.snapToScreen(0);
                                            showErrorDialog("确认密码不能为空");
                                        } else {
                                            if (!password.getText().toString().trim().equals(passwordAgain.getText().toString().trim())) {
                                                mvg.snapToScreen(0);
                                                showErrorDialog("两次密码输入不一致");
                                            } else {
                                                addDate();
                                            }
                                        }
                                    }


                                }
                            }
                        }
                    }
                }

                break;
            case R.id.birthday_textview:
                new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        // TODO Auto-generated method stub
                        //更新EditText控件日期 小于10加0
                        birthdayTextview.setText(new StringBuilder().append(year).append("-")
                                .append((month + 1) < 10 ? 0 + (month + 1) : (month + 1))
                                .append("-")
                                .append((day < 10) ? 0 + day : day));
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH)).show();
                break;

        }
    }

    private void checkAll() {
        if (TextUtils.isEmpty(marketId.getText().toString().trim())) {
            showErrorDialog("销售员ID为空");
        } else {

            if (TextUtils.isEmpty(phone.getText().toString().trim())) {
                showErrorDialog("手机号码不能为空");
            } else {
                if (!MyUtils.isMobileNO(phone.getText().toString().trim())) {
                    showErrorDialog("请输入正确的手机号码");
                } else {

                    if (TextUtils.isEmpty(password.getText().toString().trim())) {
                        showErrorDialog("密码不能为空");
                    } else {
                        if (TextUtils.isEmpty(passwordAgain.getText().toString().trim())) {
                            showErrorDialog("确认密码不能为空");
                        } else {
                            if (!password.getText().toString().trim().equals(passwordAgain.getText().toString().trim())) {
                                showErrorDialog("两次密码输入不一致");
                            } else {
                                if (capacity) {
                                    checkOk = true;
                                    mvg.snapToScreen(1);
                                } else {
                                    if (!checkOk) {
                                        if (TextUtils.isEmpty(yanzhangma.getText().toString().trim())) {
                                            showErrorDialog("验证码不能为空");
                                        } else {
                                            SMSSDK.submitVerificationCode("86", phone.getText().toString().trim(),
                                                    yanzhangma.getText().toString().trim());
                                        }
                                    } else {
                                        mvg.snapToScreen(1);
                                        checkOk = true;
                                    }

                                }

                            }
                        }
                    }
                }
            }
        }
    }

    private void showErrorDialog(String msg) {
        new FiexoDialog(RegisterActivity.this, FiexoDialog.ERROR_TYPE)
                .setTitleText(msg)
                .show();
    }

    private void checkPhone() {
        if (TextUtils.isEmpty(phone.getText().toString().trim())) {
            phone.setError("手机号码不能为空");
        } else {
            if (MyUtils.isMobileNO(phone.getText().toString().trim())) {
                SMSSDK.getVerificationCode("86", phone.getText().toString().trim());
                toast("已发送");
                time.start();//开始倒计时

            } else {
                showErrorDialog("请输入正确的手机号码");
            }
        }
    }

    public void initpermissions() {
        RegisterActivityPermissionsDispatcher.onSuccedWithCheck(this);
    }

    @NeedsPermission({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSucced() {
        initSdk();
    }

    private void initSdk() {
        if (!ready) {
            time = new TimeCount(60000, 1000);//构造CountDownTimer对象
            // 初始化短信SDK
            SMSSDK.initSDK(this, APPKEY, APPSECRET, true);
            final Handler handler = new Handler(this);
            EventHandler eventHandler = new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    Message msg = new Message();
                    msg.arg1 = event;
                    msg.arg2 = result;
                    msg.obj = data;
                    handler.sendMessage(msg);
                }
            };
            // 注册回调监听接口
            SMSSDK.registerEventHandler(eventHandler);
            ready = true;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RegisterActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCause(final PermissionRequest request) {
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onBreak() {
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onNever() {
    }

    @Override
    public boolean handleMessage(Message msg) {
        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        if (result == SMSSDK.RESULT_COMPLETE) {
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                mvg.snapToScreen(1);
                checkOk = true;
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                boolean smart = (Boolean) data;
                if (smart) {
                    //通过智能验证
                    toast("您已通过智能验证，无需再次输入验证码。");
                    yanzhangma.setVisibility(View.GONE);
                    capacity = true;
                } else {
                    //依然走短信验证
                    capacity = false;
                    yanzhangma.setVisibility(View.VISIBLE);
                }
            }
        } else if (result == SMSSDK.RESULT_ERROR) {
            ((Throwable) data).printStackTrace();
            Log.e("data", data.toString());
            toast(JsonUtil.getJsonObject(((Throwable) data).getMessage()).getString("detail"));
        }


        return false;
    }

    private void addDate() {

        MyUtils myUtils = new MyUtils();
        registPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.Registerurl + "saleNo=" + marketId.getText().toString().trim()
                + "&userPhone=" + phone.getText().toString().trim() + "&pwd=" + myUtils.getkeyBeanofStr(password.getText().toString().trim())
                + "&name=" + cgName.getText().toString().trim() +
                "&sex=" + cg_sex + "&birthday=" + birthdayTextview.getText().toString().trim() + "&cgfollower=" + restaurantNum.getText().toString().trim());
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }

    //滑动
    class MyChagneTab implements MychangetabInterface {


        @Override
        public void changecallback(int flag) {
            // TODO Auto-generated method stub
            switch (flag) {
                case 0:
                    if (checkOk) {
                        yzmRelativelayout.setVisibility(View.GONE);
                        phone.setEnabled(false);
                    }

                    break;
                case 1:

                    if (!checkOk) {
                        new FiexoDialog(context, FiexoDialog.WARNING_TYPE).setTitleText("提示")
                                .setContentText("请完成上一页面信息后点击下一步").setMCancelable(false)
                                .setConfirmText("确定").setConfirmClickListener(new FiexoDialog.OnFiexoClickListener() {
                            @Override
                            public void onClick(FiexoDialog fiexoDialog) {
                                fiexoDialog.dismiss();
                                mvg.snapToScreen(0);
                            }
                        })
                                .show();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void sendRes(int res) {
        switch (res) {
            case 0:
                toast("注册失败");
                break;
            case 1:
                //注册成功后携带账号密码 跳转到登录界面 完成自动登录
                toast("注册成功");
                Bundle bundle = new Bundle();
                bundle.putString(Constant.LOGINPHONE, phone.getText().toString().trim());
                bundle.putString(Constant.LOGINPWD, password.getText().toString().trim());
                intent.putExtras(bundle);
                startActivity(LoginActivity.class, intent);
                break;
            case 2:
                toast("账号已存在");
                break;
            case 3:
                toast("销售员ID错误");
                break;
        }
    }

    private void showRegisterdialog() {
        FiexoDialog fiexoDialog = new FiexoDialog(context, FiexoDialog.HTML_TYPE, "file:///android_asset/about.html");
        fiexoDialog.setTitleText("协议");
        fiexoDialog.setConfirmText("同意").setConfirmClickListener(new FiexoDialog.OnFiexoClickListener() {
            @Override
            public void onClick(FiexoDialog fiexoDialog) {
                fiexoDialog.dismiss();
                initpermissions();
            }
        });
        fiexoDialog.setCancelText("取消").setCancelClickListener(new FiexoDialog.OnFiexoClickListener() {
            @Override
            public void onClick(FiexoDialog fiexoDialog) {
                finish();
            }
        });
        fiexoDialog.setMCancelable(false);
        fiexoDialog.setCanceledOnTouchOutside(false);
        fiexoDialog.show();

    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            tvObtain.setBackgroundResource(R.color.main_bottom_down);
            registerGetnum.setClickable(false);
            registerGetnum.setText(millisUntilFinished / 1000 + "秒后获取");

        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            registerGetnum.setText("重新验证");
//            tvObtain.setBackgroundResource(R.color.mycolor);
            registerGetnum.setClickable(true);
        }
    }
}
